package com.banksoft.front.util;


import com.banksoft.admin.SystemCache;
import com.banksoft.admin.bean.PaySetting;
import com.banksoft.admin.bean.WxSetting;
import com.banksoft.admin.entity.Order;
import com.banksoft.common.ConfigHelper;
import com.banksoft.front.bean.*;
import com.banksoft.util.StringNumber;
import com.banksoft.util.StringUtil;
import com.banksoft.util.UUIDFactory;
import com.google.gson.Gson;
import net.sf.json.JSONObject;
import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;


/**
 * Created by Administrator on 14-11-27.
 */

public class WeixinUtil {
    private static Logger logger = LoggerFactory.getLogger(WeixinUtil.class);


    private static String accessToken_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";//获取access_token
    private static String jsapi_ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi";//获取jsapi_ticket
    public static String SEND_TEMPLATE_MESSAGE="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";//模板消息
    private static String kfSendMessage_url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=";//客服接口发送消息


    private static Map<String, TokenMessage> tokenMessageMap = new HashMap<String, TokenMessage>();
    private static long ACCESS_TOKEN_TIME = 0L; //上次获取token的时间
    private static double TOKEN_EXPIRES = 0d; //token有效期
    private static String ACCESS_TOKEN; //上次获取的token值

    private static String WEIXIN_BACK = "/front/order/payNotifyResult";
    private static String tyZf_url = "https://api.mch.weixin.qq.com/pay/unifiedorder";//统一支付接口
    public static String SIGNATURE = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=####&type=jsapi";

    //获取openId
    public static Map getOpenId(String code){
        try {
            Map map = new HashMap();
            String url = "https://api.weixin.qq.com/sns/oauth2/access_token";
            String data = "appid=" + SystemCache.AppId + "&secret=" + SystemCache.Secret + "&code=" + code + "&grant_type=authorization_code";
            logger.info("112 data:" + data);
            String jsonString = requestWxMp(url, data, "POST");
            logger.info("jsonString:" + jsonString);
            JSONObject json = JSONObject.fromObject(jsonString);
            if (json.get("openid") != null) {
                map.put("openid",json.getString("openid"));
                map.put("access_token",json.getString("access_token"));
                return map;
            } else {
                return null;
            }
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public static Map getUserInfo(String access_token,String openId){
        try{
            Map map = new HashMap();
            String url = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openId+"&lang=zh_CN";
            String result = requestWxMp(url,null,"GET");
            logger.info("得到用户信息返回结果：：" + result);
            JSONObject json = JSONObject.fromObject(result);
            if (json.get("errcode")!=null){
                map.put("errcode",json.get("errcode"));
                map.put("errmsg",json.get("errmsg"));
            }else{
                map.put("openid",json.get("openid"));
                map.put("nickname",json.get("nickname"));
                map.put("sex",json.get("sex"));
                map.put("city",json.get("city"));
                map.put("country",json.get("country"));
                map.put("province",json.get("province"));
                map.put("headimgurl",json.get("headimgurl"));
            }
            return map;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    //获取access_token
    public static String getAccessToken(WxSetting set){
        //如果有效期大于0 并且当前时间和上次获取时间差小于有效期，直接返回上次获取的token
        System.out.println("获取token:::: TOKEN_EXPIRES："+TOKEN_EXPIRES+" ACCESS_TOKEN_TIME :"+ACCESS_TOKEN_TIME+ "  :: "+(System.currentTimeMillis()-ACCESS_TOKEN_TIME < TOKEN_EXPIRES*1000)+"　　：："+ACCESS_TOKEN);
        //TOKEN_EXPIRES 这里有问题  暂时写死
        TOKEN_EXPIRES = 100;
        if(TOKEN_EXPIRES > 0 && (System.currentTimeMillis()-ACCESS_TOKEN_TIME < TOKEN_EXPIRES*1000)){
            return ACCESS_TOKEN;
        }
        String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
        String data = "&appid="+set.getAppId()+"&secret="+set.getAppSecret();
        String jsonString = null;
        try {
            jsonString = requestWxMp(token_url, data, "POST");
            Gson gson = new Gson();
            Map<String,Object> map = (Map<String, Object>) gson.fromJson(jsonString, HashMap.class);
            TOKEN_EXPIRES = (Double)map.get("expires_in");//获取token有效期
            ACCESS_TOKEN_TIME = System.currentTimeMillis();//获取token时间
            ACCESS_TOKEN = (String) map.get("access_token");
            return ACCESS_TOKEN;
        } catch (Exception e) {
            return null;
        }
    }

    //获取access_token
    public static  String createAccess_token() throws IOException {
        System.out.println("++++++++++++  "+SystemCache.AppId);
        //return getTokenMessage().getAccess_token();
         TokenMessage last = tokenMessageMap.get(SystemCache.AppId);
        if(last == null) {
            return getTokenMessage().getAccess_token();
        } else {
            long currentTime = System.currentTimeMillis();
            if(StringUtil.isNullOrEmpty(last.getExpires_in())) {
                return getTokenMessage().getAccess_token();
            }
            try {
                long expires_in = Long.parseLong(last.getExpires_in());
                //expires_in 有问题
                expires_in = 100;
                if(currentTime - last.getCreateTime() >= expires_in * 1000) {
                    return getTokenMessage().getAccess_token();
                } else {
                    return last.getAccess_token();
                }
            } catch (Exception e) {
                return getTokenMessage().getAccess_token();
            }
        }
    }

    //获取jsapi_ticket
    public static String createJsapi_ticket(String access_Token) throws IOException {
        String url = jsapi_ticket_url + "&access_token=" + access_Token;
        String resultJson = requestWxMp(url, null,"POST");

        TicketMessage ticketMessage = (TicketMessage) JSONObject.toBean(JSONObject.fromObject(resultJson), TicketMessage.class);;
        return ticketMessage.getTicket();
    }

    //重新获取token
    private static TokenMessage getTokenMessage() throws IOException {
        String url_1 = accessToken_url + "&appid=" + SystemCache.AppId + "&secret=" + SystemCache.Secret;
        String resultJson = requestWxMp(url_1, null, "POST");
        TokenMessage tokenMessage = (TokenMessage)JSONObject.toBean(JSONObject.fromObject(resultJson), TokenMessage.class);;
        tokenMessage.setCreateTime(System.currentTimeMillis());
        tokenMessageMap.put(SystemCache.AppId, tokenMessage);
        return tokenMessage;
    }

    public static String create_nonce_str() {
        return UUIDFactory.random();
    }

    public static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }

    public static String requestWxMp(String urlString, String data,String method) throws IOException {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod(method);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setDefaultUseCaches(false);

        OutputStream os = conn.getOutputStream();
        try {
            if(data!=null)
                os.write(data.getBytes("UTF-8"));
        } finally {
            if(os != null) os.close();
        }

        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            is = conn.getInputStream();
            baos = new ByteArrayOutputStream();
            int len;
            byte[] buff = new byte[1024 * 8];
            while((len = is.read(buff)) != -1)  {
                baos.write(buff, 0, len);
            }
            return new String(baos.toByteArray(), "UTF-8");
        } finally {
            if(baos != null) baos.close();
            if(is != null) is.close();
        }
    }

    //对字符串进行加密
    private static String encrypt(String str) {
        String algorithmName = "md5";
        String encryptText=null;
        try {
            MessageDigest m = MessageDigest.getInstance(algorithmName);
            m.update(str.getBytes("UTF8"));
            byte s[] = m.digest();
            return hex(s);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encryptText;
    }
    private static String hex(byte[] arr) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < arr.length; ++i) {
            sb.append(Integer.toHexString((arr[i] & 0xFF) | 0x100).substring(1,3));
        }
        return sb.toString();
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }


    //发送模板消息
    public static String templateMessage(String data) throws IOException {
        String url = SEND_TEMPLATE_MESSAGE +  WeixinUtil.createAccess_token();
        String jsonString = requestWxMp(url,data,"POST");
        return jsonString;
    }


    /**
     * 获取openId
     * @param setting
     * @param code
     * @return
     */
    public static String getOpenId(PaySetting setting, String code){
        try {
            String url = "https://api.weixin.qq.com/sns/oauth2/access_token";
            String data = "appid=" + setting.getAccountNo() + "&secret=" + setting.getAccountSecret() + "&code=" + code + "&grant_type=authorization_code";
            logger.info("data:" + data);
            String jsonString = requestWxMp(url, data, "POST");
            logger.info("jsonString:" + jsonString);
            //Map<String, String> map = new Gson().fromJson(jsonString, HashMap.class);
            JSONObject json = JSONObject.fromObject(jsonString);
            if (json.get("openid") != null) {
                return json.getString("openid");
            } else {
                return null;
            }
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    //组装数据
    public static String submitJson(PaySetting setting, HttpServletRequest request, String openId, Order order) throws IOException, DocumentException {
        String ip = request.getRemoteAddr();//获取终端ip
        if(!ip.matches("[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}")){
            ip = "127.0.0.1";
        }
        logger.info("---ip---" + ip);
        NativeZfSj nativeZfSj = createNativeZfSj(setting,openId);
        TyZf tyZf = createTyZf(ip, nativeZfSj, "JSAPI", setting.getPayKey(), order);
        nativeZfSj = tyZf(nativeZfSj, tyZf, setting.getPayKey());
        if(!StringUtil.isNullOrEmpty(nativeZfSj.getPrepay_id())) {
            PayRequest payRequest = new PayRequest();
            payRequest.setAppId(nativeZfSj.getAppid());
            payRequest.setNonceStr(UUIDFactory.random());
            payRequest.setTimeStamp(String.valueOf(System.currentTimeMillis()));
            payRequest.setSignType("MD5");
            payRequest.setPrepay_id(nativeZfSj.getPrepay_id());
            Map<String, String> map = new HashMap<String, String> ();
            map.put("appId", payRequest.getAppId());
            map.put("nonceStr", payRequest.getNonceStr());
            map.put("timeStamp", payRequest.getTimeStamp());
            map.put("signType", payRequest.getSignType());
            map.put("package", "prepay_id=" + payRequest.getPrepay_id());
            payRequest.setPaySign(weiXinZfSign(map, setting.getPayKey()));
            map.put("paySign", payRequest.getPaySign());
            //String jsonString = new Gson().toJson(map);
            String jsonString = JSONObject.fromObject(map).toString();
            jsonString = ZyUnicode.ascii2Native(jsonString);
            return jsonString;
        } else {
            return null;
        }
    }

    private static NativeZfSj createNativeZfSj(PaySetting setting,String openId){
        NativeZfSj nativeZfSj = new NativeZfSj();
        nativeZfSj.setAppid(setting.getAccountNo());
        nativeZfSj.setMch_id(setting.getPayNo());
        nativeZfSj.setProduct_id("");// 产品id 不是必填
        nativeZfSj.setOpenid(openId);
        return nativeZfSj;
    }

    //组装统一支付数据
    private static TyZf createTyZf(String ip, NativeZfSj nativeZfSj, String type, String key, Order order) {
        TyZf tyZf = new TyZf();
        tyZf.setSpbill_create_ip(ip);
        tyZf.setAppid(nativeZfSj.getAppid());
        tyZf.setMch_id(nativeZfSj.getMch_id());
        tyZf.setOpenid(nativeZfSj.getOpenid());
        tyZf.setProduct_id(nativeZfSj.getProduct_id());
        tyZf.setNonce_str(UUIDFactory.random());
        String description = "";//商品描述
        description = description +  (order.getNo());
        tyZf.setBody(description);  // 商品描述
        tyZf.setOut_trade_no(order.getNo());//  商户订单号 确保在商户这端是唯一的
        int total_fee = Integer.valueOf(StringNumber.formatPrecisionOfZero(StringNumber.mul(order.getPayAmount() + "", "100")));
        tyZf.setTotal_fee(total_fee);//  商品价格 单位为分
        tyZf.setNotify_url(ConfigHelper.GetInstance().GetConfig("ProjectDomain") + WEIXIN_BACK);
        tyZf.setTrade_type(type);
        //获取签名
        tyZf.setSign(weiXinZfSign(createTyZfMap(tyZf), key));
        return tyZf;
    }

    //组装统一支付map数据
    public static Map<String, String> createTyZfMap(TyZf tyZf) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("appid", tyZf.getAppid());
        map.put("mch_id", tyZf.getMch_id());
        map.put("nonce_str", tyZf.getNonce_str());
        map.put("body", tyZf.getBody());
        map.put("out_trade_no", tyZf.getOut_trade_no());
        map.put("total_fee", String.valueOf(tyZf.getTotal_fee()));
        map.put("spbill_create_ip", tyZf.getSpbill_create_ip());
        map.put("notify_url", tyZf.getNotify_url());
        map.put("trade_type", tyZf.getTrade_type());
        if (!StringUtil.isNullOrEmpty(tyZf.getTime_expire())) {
            map.put("time_expire", tyZf.getTime_expire());
        }
        if (!StringUtil.isNullOrEmpty(tyZf.getTime_start())) {
            map.put("time_start", tyZf.getTime_start());
        }
        if (!StringUtil.isNullOrEmpty(tyZf.getGoods_tag())) {
            map.put("goods_tag", tyZf.getGoods_tag());
        }
        if (!StringUtil.isNullOrEmpty(tyZf.getOpenid())) {
            map.put("openid", tyZf.getOpenid());
        }
        if (!StringUtil.isNullOrEmpty(tyZf.getDevice_info())) {
            map.put("device_info", tyZf.getDevice_info());
        }
        if (!StringUtil.isNullOrEmpty(tyZf.getAttach())) {
            map.put("attach", tyZf.getAttach());
        }
        if (!StringUtil.isNullOrEmpty(tyZf.getProduct_id())) {
            map.put("product_id", tyZf.getProduct_id());
        }
        return map;
    }

    //调用统一支付接口
    private static NativeZfSj tyZf(NativeZfSj nativeZfSj, TyZf tyZf, String key) throws IOException, DocumentException {
        String xmlString = dyTyZf(tyZf);
        logger.info("---xmlString---" + xmlString);
        Map<String, String> returnTyZfXmlMap = MessageUtil.parseXmlByString(xmlString);
        //判断调用统一支付接口后返回来的数据 是否返回数据正确。
        if ("FAIL".equals(returnTyZfXmlMap.get("return_code"))) {
            nativeZfSj.setReturn_code("FAIL");
            if(returnTyZfXmlMap.get("return_msg") == null) {
                nativeZfSj.setReturn_msg("通信失败");
            } else {
                nativeZfSj.setReturn_msg(returnTyZfXmlMap.get("return_msg"));
            }
        } else if ("FAIL".equals(returnTyZfXmlMap.get("result_code"))) {
            nativeZfSj.setReturn_code("FAIL");
            if(returnTyZfXmlMap.get("return_msg") == null) {
                nativeZfSj.setReturn_msg("重新操作或者联系商家");
            } else {
                nativeZfSj.setReturn_msg(returnTyZfXmlMap.get("return_msg"));
            }
            nativeZfSj.setResult_code("FAIL");
            if(returnTyZfXmlMap.get("err_code_des") == null) {
                nativeZfSj.setErr_code_des("业务失败");
            } else {
                nativeZfSj.setErr_code_des(returnTyZfXmlMap.get("err_code_des"));
            }
        } else {
            //判断签名是否成功
            String returnTyZfXmlMapSign = returnTyZfXmlMap.get("sign");
            returnTyZfXmlMap.remove("sign");
            String returnSign = weiXinZfSign(returnTyZfXmlMap, key);
            if (returnSign.equals(returnTyZfXmlMapSign)) {
                String prepay_id = returnTyZfXmlMap.get("prepay_id");//预支付id
                String appid = returnTyZfXmlMap.get("appid");
                String mch_id = returnTyZfXmlMap.get("mch_id");
                nativeZfSj.setReturn_code("SUCCESS");
                nativeZfSj.setPrepay_id(prepay_id);
                nativeZfSj.setResult_code("SUCCESS");
                nativeZfSj.setAppid(appid);
                nativeZfSj.setMch_id(mch_id);
                nativeZfSj.setNonce_str(UUIDFactory.random());
                nativeZfSj.setSign(createNativeZfSjBackMap(nativeZfSj, key));
            } else {
                //签名失败
                nativeZfSj.setReturn_code("FAIL");
                if(returnTyZfXmlMap.get("return_msg") == null) {
                    nativeZfSj.setReturn_msg("签名失败");
                } else {
                    nativeZfSj.setReturn_msg(returnTyZfXmlMap.get("return_msg"));
                }
            }
        }
        logger.info("---weixin error --" + nativeZfSj.getReturn_msg());
        return nativeZfSj;
    }

    //调用统一支付接口 返回预支付订单号
    public static String dyTyZf(TyZf t) throws IOException {
        String data = MessageUtil.tyZfToXml(t);
        String xmlString = requestWxMp(tyZf_url, data,"POST");
        return xmlString;
    }

    //微信支付签名
    public static String weiXinZfSign(Map<String, String> signMap, String key) {
        Collection<String> keyset= signMap.keySet();
        List<String> list = new ArrayList<String>(keyset);

        //对key键值按字典升序排序
        Collections.sort(list);

        String signTemp = "";
        for(String s : list) {
            if("".equals(signTemp)) {
                signTemp = s + "=" + signMap.get(s);
            } else {
                signTemp = signTemp + "&" + s + "=" + signMap.get(s);
            }
        }
        if(!StringUtil.isNullOrEmpty(key)) {
            signTemp = signTemp + "&" + "key=" + key;
        }
        signTemp = encrypt(signTemp).toUpperCase();
        return signTemp;
    }


    //创建调用统一支付接口后返回数据时成功时生成签名所需要的数据
    private static String createNativeZfSjBackMap(NativeZfSj nativeZfSj, String key) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("return_code", nativeZfSj.getReturn_code());
        if (!StringUtil.isNullOrEmpty(nativeZfSj.getReturn_msg())) {
            map.put("return_msg", nativeZfSj.getReturn_msg());
        }
        map.put("appid", nativeZfSj.getAppid());
        map.put("mch_id", nativeZfSj.getMch_id());
        map.put("nonce_str", nativeZfSj.getNonce_str());
        map.put("prepay_id", nativeZfSj.getPrepay_id());
        map.put("result_code", nativeZfSj.getResult_code());
        if (!StringUtil.isNullOrEmpty(nativeZfSj.getErr_code_des())) {
            map.put("err_code_des", nativeZfSj.getErr_code_des());
        }
        String sign = weiXinZfSign(map, key);
        return sign;
    }


    /**
     * 微信支付结果通知
     * @param requestMap
     * @param key
     * @return
     * @throws UnsupportedEncodingException
     */
    public static Object notify( Map<String, String> requestMap,String key) throws UnsupportedEncodingException {
        // 将请求、响应的编码均设置为UTF-8（防止中文乱码）
        String respMessage = ""; //
        String orderId="";
        //  TyNoticeSj returnTyNoticeSj = null;
        TyNoticeSj tyNoticeSj = new TyNoticeSj();
        // xml请求解析
        try {
            System.out.println("--------  "+requestMap);
            orderId = requestMap.get("out_trade_no");
            if ("FAIL".equals(requestMap.get("return_code"))) {
                tyNoticeSj.setReturn_code("FAIL");
                tyNoticeSj.setReturn_msg("通信失败");
                respMessage = MessageUtil.tyNoticeToXml(tyNoticeSj);
            } else if ("FAIL".equals(requestMap.get("result_code"))) {
                tyNoticeSj.setReturn_code("FAIL");
                tyNoticeSj.setReturn_msg(requestMap.get("err_code_des"));
                respMessage = MessageUtil.tyNoticeToXml(tyNoticeSj);
            } else {
                //判断签名
                String returnSign = requestMap.get("sign");
                requestMap.remove("sign");
                if (requestMap.get("orderId") != null) {
                    requestMap.remove("orderId");
                }
                String zzSign = weiXinZfSign(requestMap, key);
                if (zzSign.equals(returnSign)) {
                    tyNoticeSj = createBackTyZfNotice(requestMap);
                    tyNoticeSj.setSign(returnSign);
                    tyNoticeSj.setReturn_code("SUCCESS");
                    respMessage = MessageUtil.tyNoticeToXml(tyNoticeSj);
                } else {//签名失败
                    tyNoticeSj.setReturn_code("FAIL");
                    tyNoticeSj.setReturn_msg("签名失败");
                    respMessage = MessageUtil.tyNoticeToXml(tyNoticeSj);
                }
            }
        } catch (Exception e) {
            tyNoticeSj.setReturn_code("FAIL");
            tyNoticeSj.setReturn_msg("参数格式错误");
            respMessage = MessageUtil.tyNoticeToXml(tyNoticeSj);
        }
        return new Object[]{tyNoticeSj, respMessage, orderId};
    }


    //微信通用通知商家时返回来的信息数据组装成对象
    private static TyNoticeSj createBackTyZfNotice(Map<String, String> requestMap) {
        TyNoticeSj tyNoticeSj = new TyNoticeSj();
        tyNoticeSj.setReturn_code(requestMap.get("return_code"));
        if (requestMap.get("return_msg") != null) {
            tyNoticeSj.setReturn_msg(requestMap.get("return_msg"));
        }
        tyNoticeSj.setAppid(requestMap.get("appid"));
        tyNoticeSj.setMch_id(requestMap.get("mch_id"));
        if (requestMap.get("device_info") != null) {
            tyNoticeSj.setDevice_info(requestMap.get("device_info"));
        }
        tyNoticeSj.setNonce_str(requestMap.get("nonce_str"));
        tyNoticeSj.setResult_code(requestMap.get("result_code"));
        if (requestMap.get("err_code") != null) {
            tyNoticeSj.setErr_code(requestMap.get("err_code"));
        }
        if (requestMap.get("err_code_des") != null) {
            tyNoticeSj.setErr_code_des(requestMap.get("err_code_des"));
        }
        tyNoticeSj.setOpenid(requestMap.get("openid"));
        tyNoticeSj.setIs_subscribe(requestMap.get("is_subscribe"));
        tyNoticeSj.setTrade_type(requestMap.get("trade_type"));
        tyNoticeSj.setBank_type(requestMap.get("bank_type"));
        tyNoticeSj.setTotal_fee(Integer.parseInt(requestMap.get("total_fee")));
        tyNoticeSj.setCoupon_fee(requestMap.get("coupon_fee"));
        if (requestMap.get("fee_type") != null) {
            tyNoticeSj.setFee_type(requestMap.get("fee_type"));
        }
        tyNoticeSj.setTransaction_id(requestMap.get("transaction_id"));
        tyNoticeSj.setOut_trade_no(requestMap.get("out_trade_no"));
        if (requestMap.get("attach") != null) {
            tyNoticeSj.setAttach(requestMap.get("attach"));
        }
        tyNoticeSj.setTime_end(requestMap.get("time_end"));
        return tyNoticeSj;
    }

    //获取access_token
    public static  String createAccess_token(WxSetting weiXinSetting) throws IOException {
        TokenMessage last = tokenMessageMap.get(weiXinSetting.getAppId());
        if(last == null) {
            return getTokenMessage(weiXinSetting).getAccess_token();
        } else {
            long currentTime = System.currentTimeMillis();
            if(StringUtil.isNullOrEmpty(last.getExpires_in())) {
                return getTokenMessage(weiXinSetting).getAccess_token();
            }
            try {
                long expires_in = Long.parseLong(last.getExpires_in());
                if(currentTime - last.getCreateTime() >= expires_in * 1000l) {
                    return getTokenMessage(weiXinSetting).getAccess_token();
                } else {
                    return last.getAccess_token();
                }
            } catch (Exception e) {
                return getTokenMessage(weiXinSetting).getAccess_token();
            }
        }
    }

    //重新获取token
    private static TokenMessage getTokenMessage(WxSetting weiXinSetting) throws IOException {
        String url_1 = accessToken_url + "&appid=" + weiXinSetting.getAppId() + "&secret=" + weiXinSetting.getAppSecret();
        String resultJson = ResponseUtil.requestByPost(url_1, "");
        TokenMessage tokenMessage = (TokenMessage) JSONHelper.fromJson(resultJson, TokenMessage.class);
        tokenMessage.setCreateTime(System.currentTimeMillis());
        tokenMessageMap.put(weiXinSetting.getAppId(), tokenMessage);
        return tokenMessage;
    }

    //客服接口发送消息
    public static String kfSendMessage(WxSetting wxSetting, String sendMes) throws IOException {
        String url = kfSendMessage_url + createAccess_token();
        String jsonString = ResponseUtil.requestByPost(url, sendMes);
        return jsonString;
    }
}
